from scapy.all import *
import SSHConnection
from Call_Wechat import *


## ========================================================================== ##
## ------------------------ USER CONFIGURATION FLAGS ------------------------ ##
## ========================================================================== ##在路上


## 时间设置
local_catch_traffic_time = 40   # 本机收集流量时间
shutdown_wait = 1               # 一次发送完后等待时间

## 其他设置
# 本机IP
local_IP = 'xx.xx.xx.xx'
# 本机网卡       两种方式获取。 scapy中的show_interfaces()方法；命令行中ipconfig /all
local_iface = 'Realtek RTL8188EU Wireless XXXX'
# 消息交互次数
times = 1000


# 服务器设置
# 网关
gateway_catch_traffic_time = 40  # 网关每次抓流量时长
gateway_dict = {'host': 'xx.xx.xx.xx', 'port': 2222, 'username': '', 'pwd': ''}
gateway_path = '/media/work/'


server_IP = 'xx.xx.xx.xx'


# 本机流量收集
def catch_traffic():
    IPfilter = 'host ' + server_IP + ' and tcp'
    PTKS = sniff(filter=IPfilter, iface=local_iface, timeout=local_catch_traffic_time)
    pcapname = 'E:\\WeChatPcap\\wechatcall1\\' + datetime.now().strftime('%Y%m%d_%H%M_%S_') + \
        'call' + '.pcap'
    wrpcap(pcapname, PTKS)

# 网关收集流量
def catch_traffic_gateway(gatewaySSH, no):
    gateway_cmd = 'sudo timeout ' + str(gateway_catch_traffic_time) + ' tcpdump host ' + server_IP + ' -s0 -G ' + str(gateway_catch_traffic_time) + ' -w ' + gateway_path + '/%Y_%m%d_%H%M_%S.pcap'
    gatewaySSH.cmd(gateway_cmd, sudo=True)
    # timeout 运行有时间限制的linux命令


# 自动打电话
def wechat_call(receiver_name):
    wechatcall = CallWechat(receiver_name)  # 考虑是给同一个人一直打电话 然后采集数据 还是说给多个人打电话采集数据 然后这个循环的次数怎么确定，如何跟sniff进行一个同步
    wechatcall.call()
    time.sleep(1)
    time.sleep(35)# 给35秒时间，包括从点击接听按钮+接通+持续通话时间
    # 这边的从接电话 到下次打电话的时间，应当大于采集流量的时间 time.sleep(40)
    wechatcall.close_call()

# 主函数
def capture():
    # 连接网关
    gatewaySSH = SSHConnection.SSHConnection(gateway_dict)
    gatewaySSH.connect()

    with open('E:\\WeChatPcap\\log\\log.txt', 'a') as log_record:


        for i in range(times):
            print("第%d趟开始。" % i, file=log_record)

            # # ========================= 网关开始收集流量 =========================#
            catch_traffic_gateway_thread = threading.Thread(target=catch_traffic_gateway, args=(gatewaySSH, 'no'))
            catch_traffic_gateway_thread.start()

            # ========================= 本机开始收集流量 =========================#
            catch_traffic_thread = threading.Thread(target=catch_traffic, args=())
            catch_traffic_thread.start()


            # ========================= 自动拨打电话 =========================#
            wechat_call('在路上')

            #catch_traffic_thread.join()  # 主线程等待子线程
            catch_traffic_thread.join()   #30s时间足够长，可以发送和接收完毕信息。这里，join一下能保证时间是30s
            catch_traffic_gateway_thread.join()

            time.sleep(shutdown_wait)

        gatewaySSH.close()


if __name__ == '__main__':
    capture()
